package com.ytjj.qmyx.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.annotation.OperLog;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.ReturnGoodsDao;
import com.ytjj.qmyx.admin.mapper.ReturnDutyMapper;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.ReturnDuty;
import com.ytjj.qmyx.admin.model.dto.ReturnDutyDto;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.OrdersForbidResponse;
import com.ytjj.qmyx.admin.model.response.ReturnGoodsResponse;
import com.ytjj.qmyx.admin.service.ExpressService;
import com.ytjj.qmyx.admin.service.ReturnDutyService;
import com.ytjj.qmyx.admin.service.ReturnGoodsService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.OrdersMapper;
import com.ytjj.qmyx.mall.model.Orders;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 * 订单售后相关
 */
@RestController
@RequestMapping("/returnGoods")
@Slf4j
public class ReturnGoodsController {

	@Resource
	private ReturnGoodsService returnGoodsService;
	@Resource
	private SupplyApiConfig supplyApiConfig;

	@Resource
	private ReturnDutyMapper returnDutyMapper;
	@Resource
	private ReturnGoodsDao returnGoodsDao;

	@Autowired
	private ReturnDutyService returnDutyService;

	@Resource
	private OrdersDao rdersDao;

	@Resource
	private ExpressService expressService;

	@PostMapping("/list")
	@OperLog(operModule = "退货管理", operDesc = "列表", operType = SysLogConstants.OPERATION_SELECT)
	public CommonResult selectList(@RequestBody ReturnGoodsRequest request) {
		return CommonResult.success(returnGoodsService.selectList(request));
	}

	@PostMapping("/returnList")
	@OperLog(operModule = "退货管理", operDesc = "列表", operType = SysLogConstants.OPERATION_SELECT)
	public CommonResult selectReturnList(@RequestBody ReturnGoodsRequest request) {
		return CommonResult.success(returnGoodsService.selectReturnList(request));
	}

	@GetMapping("/getDetailById")
	@OperLog(operModule = "退货管理", operDesc = "详情", operType = SysLogConstants.OPERATION_SELECT)
	public CommonResult getReturnGoodsDetail(@RequestParam Integer id) {
		return CommonResult.success(returnGoodsService.getReturnGoodsDetailInfo(id));
	}


	@GetMapping("/getSupplyChainDetailByIdAnd")
	@OperLog(operModule = "退货管理-供应链", operDesc = "详情", operType = SysLogConstants.OPERATION_SELECT)
	public CommonResult getSupplyChainReturnGoodsDetail(@RequestParam Integer id) {
		return CommonResult.success(returnGoodsService.getReturnGoodsDetailInfoBySupplyChain(id));
	}

	@GetMapping("/auditSuccess")
	@OperLog(operModule = "退货管理", operDesc = "客服审核成功", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult auditSuccess(@RequestParam Integer id) {
		return returnGoodsService.auditSuccess(id);
	}

	@PostMapping("/batchAuditSuccess")
	@OperLog(operModule = "退货管理", operDesc = "客服审核成功", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult batchAuditSuccess(@RequestBody List<Integer> ids) {
		return returnGoodsService.batchAuditSuccess(ids);
	}

	/**
	 * 客服审核不通过
	 * @param id 退货id
	 * @param serviceRemarks 不通过原因
	 * @param rejectType 不通过类型 1.修改提交 2.不再受理
	 * @return
	 */
	@GetMapping("/auditFail")
	@OperLog(operModule = "退货管理", operDesc = "客服审核失败", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult auditFail(@RequestParam Integer id, @RequestParam String serviceRemarks, @RequestParam String rejectType) {
		return CommonResult.success(returnGoodsService.auditFail(id, serviceRemarks,rejectType));
	}

	@PostMapping("/syncReturnInfo")
	@OperLog(operModule = "退货管理", operDesc = "编辑退货信息", operType = SysLogConstants.OPERATION_ADD)
	public CommonResult syncReturnInfo(@RequestBody ReturnGoodsSyncRequest request) {
		returnGoodsService.synvReturnInfo(request);
		return CommonResult.success();
	}

	@GetMapping("/refundGoods")
	@OperLog(operModule = "退货管理", operDesc = "退货管理-退款", operType = SysLogConstants.OPERATION_ADD)
	public CommonResult refundGoods(@RequestParam Integer id, @RequestParam String refundDesc){
		return CommonResult.success(returnGoodsService.refundGoods(id, refundDesc));
	}

	@GetMapping("/syncReturnRegister")
	@OperLog(operModule = "退货管理", operDesc = "同步原路返回页", operType = SysLogConstants.OPERATION_ADD)
	public CommonResult syncReturnRegister() {
		returnGoodsService.syncReturnRegister(null);
		return CommonResult.success();
	}

	@GetMapping("/syncReturnRegisterByMark")
	public void syncReturnRegisterByMark() {
		try {
			log.info("syncReturnRegisterByMark======");
			returnGoodsService.syncReturnRegister("mark");
		} catch (Exception e) {
			log.error("客服标记订单同步原路返回页报错,{}",e);
		}
	}

	@GetMapping("/syncReturnRegisterByRpc")
	public void syncReturnRegisterByRpc() {
		try {
			returnGoodsService.syncReturnRegister("2");
		} catch (Exception e) {
			log.error("待退款同步原路返回页报错,{}",e);
		}
	}

	/**
	 * 退货管理的数据批量导入到原路返回页
	 * @param returnGoodsRequest
	 * @return
	 */
	@PostMapping("/batchSyncReturnRegister")
	public CommonResult batchSyncReturnRegister(@RequestBody ReturnGoodsReq returnGoodsRequest){
		returnGoodsService.batchSyncReturnRegister(returnGoodsRequest.getReturnGoodsIds());
		return CommonResult.success();
	}

	/**
	 * 退货管理的数据导入到原路返回页
	 * @param returnGoodsId
	 * @return
	 */
	@GetMapping("/syncReturnRegisterById")
	public void syncReturnRegisterById(@RequestParam Integer returnGoodsId){
		returnGoodsService.syncReturnRegisterById(returnGoodsId);
	}



	/**
	 * 移除退货管理的数据
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteReturnGoods")
	public CommonResult deleteReturnGoods(@RequestParam Integer id){
		log.debug("===退货管理移除==={}，{}", id, UserUtil.getPrincipal());
		return returnGoodsService.deleteReturnGoods(id);
	}

	/**
	 * 撤销退货管理的数据
	 * @param id
	 * @return
	 */
	@GetMapping("/removeReturnGoods")
	@OperLog(operModule = "退货管理", operDesc = "撤销售后申请", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult removeReturnGoods(@RequestParam Integer id){
		log.info("===退货管理移除==={}，{}", id, UserUtil.getPrincipal());
		return returnGoodsService.removeReturnGoods(id);
	}

	/**
	 * 从客服订单详情页同步到退货管理
	 * @param returnGoodsRequest
	 * @return
	 */
	@PostMapping("/creatReturnGoods")
	public CommonResult creatReturnGoods(@RequestBody ReturnGoodsReq returnGoodsRequest){
		return returnGoodsService.creatReturnGoods(returnGoodsRequest);
	}

	/**
	 * 订单物流
	 * @param tel
	 * @param expressCompany
	 * @param expressNo
	 * @return
	 */
	@GetMapping("/getLogistics")
	public CommonResult getLogistics(@RequestParam String tel, @RequestParam String expressCompany, @RequestParam String expressNo) {
		if (tel != null && expressCompany != null && expressNo != null) {
			Map<String, String> request = new HashMap<>();
			request.put("expressCode", expressCompany);
			request.put("expressNo", expressNo);
			request.put("tel", tel);
			String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/express/getLogisticsInfo",
					request, supplyApiConfig.getHeadsMap());
			CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
			return commonResult;
		} else {
			return CommonResult.success(new Object[]{});
		}
	}

	/**
	 * 退款物流
	 * @param tel
	 * @param expressCompany
	 * @param expressNo
	 * @return
	 */
	@GetMapping("/returnGoodsGetLogistics")
	public CommonResult returnGoodsGetLogistics(@RequestParam String tel, @RequestParam String expressCompany, @RequestParam String expressNo) {
		if (tel != null && expressCompany != null && expressNo != null) {

			Map<String,String> map = new HashMap<>();
			map.put("tel",tel);
			map.put("expressCompany",expressCompany);
			map.put("expressNo",expressNo);
			String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getLogistics",map, supplyApiConfig.getHeadsMap());
			CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
			if (null == commonResult || 200 != commonResult.getCode() || commonResult.getData() == null) {
				return CommonResult.success("暂无物流信息！");
			}
			try {
				log.info("===commonResult==={}", JSONObject.toJSONString(commonResult));
				List<QueryTrackData> data = JSONArray.parseArray(commonResult.getData().toString(), QueryTrackData.class);
				return CommonResult.success(data);
			} catch (Exception e) {
				log.error("==={}===", e);
			}
			return CommonResult.success();
		} else {
			return CommonResult.success();
		}
	}

	/**
	 * 退货数据,手动修改退货状态为已寄回待处理
	 */
	@GetMapping("/updateStatus")
	public CommonResult updateStatus(@RequestParam Integer id){
		log.info("===update return goods status:{}", id);
		Integer count = returnGoodsService.updateStatus(id);
		if (count > 0){
			return CommonResult.success(count);
		}
		return CommonResult.failed();
	}

	/**
	 * 根据供应商id获取供应商退货地址
	 * @param bankerId
	 * @return
	 */
	@GetMapping("/getReturnAddressByBankerId")
	public CommonResult getReturnAddressByBankerId(@RequestParam Integer bankerId){
		return CommonResult.success(returnGoodsService.newGetReturnAddressByBankerId(bankerId));
	}


	/**
	 * 新增地址
	 */
	@PostMapping("/insertAddress")
	public CommonResult insertAll(@RequestBody BankerAddressRequest request) {
		returnGoodsService.insertAddress(request);
		return CommonResult.success();
	}

	//获取省份
	@GetMapping("/getProvince")
	public CommonResult getProvince(@RequestParam(value="id",required=false) Integer id) {
		return returnGoodsService.getProvince(id);
	}

	//根据省份id
	@GetMapping("/getCity")
	public CommonResult getCity(@RequestParam(value="id",required=false) Integer id) {
		return returnGoodsService.getCity(id);
	}

	//根据城市id
	@GetMapping("/getArea")
	public CommonResult getArea(@RequestParam(value="id",required=false) Integer id) {
		return returnGoodsService.getArea(id);
	}


	@PostMapping("/getReturnDuty")
	public CommonResult<ReturnDutyDto> getReturnDuty(@RequestBody ReturnDutyDto param) {
		return CommonResult.success(returnDutyService.getReturnDuty(param));
	}

	@PostMapping("/saveOrUpdateReturnDuty")
	@OperLog(operModule = "退货责任", operDesc = "编辑退货责任", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult<ReturnDutyDto> saveOrUpdateReturnDuty(@RequestBody ReturnDutyDto param) {
		Assert.notNull(param.getServiceNo(), "服务单号不能为空!");
		Assert.notNull(param.getReasonType(), "原因类型不能为空!");
		Assert.notNull(param.getReasonSecondType(), "问题归类不能为空!");
		ReturnDuty paramEntity = new ReturnDuty();
		paramEntity.setServiceNo(param.getServiceNo());
		ReturnDuty returnDuty = returnDutyMapper.selectOne(paramEntity);
		if(param.getReturnDutyFee() != null){
			ReturnGoodsResponse returnGoods = returnGoodsDao.selectByServiceNo(param.getServiceNo());
			Orders orderInfo = rdersDao.getOrdersByOrderInfoId(returnGoods.getOrdersInfoId());
			if(param.getReturnDutyFee().compareTo(orderInfo.getRealTotalMoney()) >0){
				throw new ApiException("金额不能大于用户的支付金额！");
			}
		}
		if (null == returnDuty) {
			returnDutyService.saveReturnDuty(param);
		} else {
			param.setId(returnDuty.getId());
			returnDutyService.updateReturnDuty(param);
		}
		return CommonResult.success();
	}

	/**
	 * 自动保存售后责任
	 * @param serviceNo
	 */
	@GetMapping("/saveReturnDuty")
	public void saveReturnDuty(@RequestParam String serviceNo){
		ReturnDutyDto param = new ReturnDutyDto();
		param.setServiceNo(serviceNo);
		param.setReasonType(2);
		param.setOrderType(0);
		param.setReasonSecondType(7);
		param.setReasonDetail("无理由、多/错拍、不喜欢、不想要");
		returnDutyService.saveReturnDuty(param);
	}

	/**
	 * 获取锁单详情
	 * @param id 锁单唯一id
	 */
	@GetMapping("/getLockOrderInfo")
	public CommonResult<OrdersForbidResponse> getLockOrderInfo(Integer id){
		OrdersForbidResponse lockOrderInfo = returnGoodsService.getLockOrderInfo(id);
		return CommonResult.success(lockOrderInfo);
	}

	/**
	 * 锁单或者解除锁单
	 */
	@PostMapping("/lockOrder")
	@OperLog(operModule = "订单锁单", operDesc = "锁单或者解除锁单", operType = SysLogConstants.OPERATION_UPDATE)
	public CommonResult lockOrder(@Validated @RequestBody OrdersForbidRequest ordersForbidRequest){
		return returnGoodsService.lockOrder(ordersForbidRequest);
	}

	/**
	 * 分页获取锁单信息
	 */
	@PostMapping("/getLockOrderInfoByPage")
	public CommonResult<CommonPage<OrdersForbidResponse>> getLockOrderInfoByPage(@RequestBody OrdersForbidPageRequest request){
		CommonPage<OrdersForbidResponse> lockOrderInfoByPage = returnGoodsService.getLockOrderInfoByPage(request);
		return CommonResult.success(lockOrderInfoByPage);
	}

	/**
	 *
	 * 根据快递单号获取物流公司
	 */
	@GetMapping("/queryExpressCompany")
	public CommonResult queryExpressCompany(@RequestParam String num) {
		return CommonResult.success(expressService.queryExpressCompany(num));
	}

}
